package tt.dz.egobus.servicemanager.controller.drivermanager;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import tt.dz.egobus.api.ResponseBack;
import tt.dz.egobus.api.page.Filter;
import tt.dz.egobus.api.page.Page;
import tt.dz.egobus.api.page.Pageable;
import tt.dz.egobus.api.usercenter.staff.StaffBack;
import tt.dz.egobus.bean.CodeStatus;
import tt.dz.egobus.servicemanager.base.controller.CommonBinderController;
import tt.dz.egobus.servicemanager.bean.PagingationStart;
import tt.dz.egobus.servicemanager.core.exception.BusinessException;
import tt.dz.egobus.servicemanager.entities.DriverRegisterBusRelative;
import tt.dz.egobus.servicemanager.service.DriverManagerService;
import tt.dz.egobus.servicemanager.util.DubboManagerPagableUtils;
import tt.dz.egobus.servicemanager.util.MapGetUtils;
import tt.dz.egobus.servicemanager.util.PojoConvertVoUtils;
import tt.dz.egobus.servicemanager.vo.DriverViewVo;
import tt.dz.egobus.servicemanager.vo.JsonBack;
import tt.dz.egobus.vo.KV;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static tt.dz.egobus.servicemanager.bean.ServiceManagerCodeStatus.DRIVER_DELETE_ERROR;
import static tt.dz.egobus.servicemanager.bean.ServiceManagerCodeStatus.SYSTEM_CODE_ERROR;

/**
 * @author Anson
 * @date 17-4-1
 * @name 司机的管理
 * @since 1.0.3
 */
@RestController
@RequestMapping("/driver")
public class DriverController extends CommonBinderController {
    private static final Logger LOGGER = LoggerFactory.getLogger(DriverController.class);


    @Autowired
    @Qualifier("driverManagerDubboServiceImpl")
    private DriverManagerService driverManagerService;

    @RequestMapping("/all")
    public JsonBack<List<DriverViewVo>> queryAll() {
        JsonBack<List<DriverViewVo>> back = null;
        try {
            ResponseBack<List<StaffBack>> staffBackResponse = driverManagerService.queryAll();
            if (staffBackResponse.isSuccess()) {
                List<StaffBack> staffBacks = staffBackResponse.getResult();
                List<DriverViewVo> datas = PojoConvertVoUtils.staffBackListConvertDriverViewVos(staffBacks);
                back = JsonBack.success(datas);
            } else {
                back = JsonBack.instance(staffBackResponse, null);
            }
        } catch (BusinessException e) {
            back = JsonBack.error(e);
            LOGGER.error("新增参数", e);
        } catch (Exception e) {
            back = JsonBack.error(SYSTEM_CODE_ERROR);
            LOGGER.error("新增参数", e);
        }
        return back;
    }

    /**
     * @author Anson
     * @date 17-4-18
     * @name 分页查询
     * @since 1.0.4
     */
    @RequestMapping("/pageStart")
    public JsonBack<PagingationStart<DriverViewVo>> pagationStart(@RequestParam Map<String, Object> param) {
        JsonBack<PagingationStart<DriverViewVo>> back = null;
        try {
            Pageable pageable = new Pageable();
            int start = MapGetUtils.getAndRemoveDigits(param, "start");
            int maxResult = MapGetUtils.getAndRemoveDigits(param, "limit");
            int pageNumber = start / maxResult + 1;
            param = this.convertParams(param);
            pageable.setPageNumber(pageNumber);
            pageable.setPageSize(maxResult);
            DubboManagerPagableUtils utils = new DubboManagerPagableUtils();
            List<Filter> filters = utils.adaptcher(param);
            pageable.setFilters(filters);
            ResponseBack<Page<StaffBack>> staffBackResponse = driverManagerService.queryStaffPage(pageable);
            if (staffBackResponse.isSuccess()) {
                Page<StaffBack> staffBacks = staffBackResponse.getResult();
                PagingationStart<DriverViewVo> pagingationStart = new PagingationStart<DriverViewVo>();
                if (staffBacks != null) {
                    List<StaffBack> staffBacks1 = staffBacks.getContent();
                    List<DriverViewVo> driverViewVos = PojoConvertVoUtils.staffBackListConvertDriverViewVos
                            (staffBacks1);
                    pagingationStart.setPageSize(maxResult);
                    pagingationStart.setList(driverViewVos);
                    pagingationStart.setAllRow(Long.valueOf(staffBacks.getTotal()).intValue());
                }
                back = JsonBack.success(pagingationStart);
            } else {
                back = JsonBack.instance(staffBackResponse, null);
            }
        } catch (BusinessException e) {
            back = JsonBack.error(e);
            LOGGER.error("[pageStart]分页查询", e);
        } catch (Exception e) {
            back = JsonBack.error(SYSTEM_CODE_ERROR);
            LOGGER.error("[pageStart]分页查询", e);
        }
        return back;
    }

    /**
     * @author Anson
     * @date 17-4-18
     * @name 判断某个身份证是否已经存在记录
     * @since 1.0.4
     */
    @RequestMapping("/isExistsCardNo")
    public JsonBack<Boolean> judgeStaffExists(@RequestParam("idCard") String idCard) {
        JsonBack<Boolean> back = null;
        try {
            ResponseBack<Boolean> isExits = driverManagerService.judgeStaffExists(idCard);
            if (isExits.isSuccess()) {
                back = JsonBack.success(isExits.getResult());
            } else {
                back = JsonBack.instance(isExits, null);
            }
        } catch (BusinessException e) {
            back = JsonBack.error(e);
            LOGGER.error("新增参数", e);
        } catch (Exception e) {
            back = JsonBack.error(SYSTEM_CODE_ERROR);
            LOGGER.error("新增参数", e);
        }
        return back;
    }

    /**
     * @author Anson
     * @date 17-4-18
     * @name 新增
     * @since 1.0.4
     */
    @RequestMapping("/insert")
    public JsonBack<DriverViewVo> insert(@ModelAttribute @Valid DriverViewVo v, BindingResult result) {
        JsonBack<DriverViewVo> back = null;
        try {
            if (result.hasErrors()) {
                //如果没有通过,跳转提示
                JsonBack.throwErrorException(result);
            }
            ResponseBack<StaffBack> staffBack = driverManagerService.createStaff(v.getRealName(), v.getIdCard());
            if (staffBack.isSuccess()) {
                StaffBack result1 = staffBack.getResult();
                DriverViewVo vo = new DriverViewVo();
                back = JsonBack.success(result1 == null ? vo : vo.view(result1));
            } else {
                back = JsonBack.instance(staffBack, null);
            }
        } catch (BusinessException e) {
            back = JsonBack.error(e);
            LOGGER.error("新增参数", e);
        } catch (Exception e) {
            back = JsonBack.error(SYSTEM_CODE_ERROR);
            LOGGER.error("新增参数", e);
        }
        return back;
    }

    /**
     * @author Anson
     * @date 17-4-18
     * @name 更新
     * @since 1.0.4
     */
    @RequestMapping("/update")
    public JsonBack<DriverViewVo> update(@ModelAttribute @Valid DriverViewVo v, BindingResult result) {
        JsonBack<DriverViewVo> back = null;
        try {
            if (result.hasErrors()) {
                //如果没有通过,跳转提示
                JsonBack.throwErrorException(result);
            }
            ResponseBack<StaffBack> staffBack = driverManagerService.updataStaff(v.getId(), v.getRealName(), v
                    .getIdCard());
            if (staffBack.isSuccess()) {
                DriverViewVo vo = new DriverViewVo();
                StaffBack result1 = staffBack.getResult();
                back = JsonBack.success(result1 == null ? vo : vo.view(result1));
            } else {
                back = JsonBack.instance(staffBack, null);
            }
        } catch (BusinessException e) {
            back = JsonBack.error(e);
            LOGGER.error("修改参数", e);
        } catch (Exception e) {
            back = JsonBack.error(SYSTEM_CODE_ERROR);
            LOGGER.error("修改参数", e);
        }
        return back;
    }

    /**
     * @author Anson
     * @date 17-4-18
     * @name 删除
     * @since 1.0.4
     */
    @RequestMapping("/delete")
    public JsonBack<Boolean> delete(@RequestParam("id") String id) {
        JsonBack<Boolean> back = null;
        try {
            KV<Boolean, String> isDelete = driverManagerService.deleteStaff(id);
            if (isDelete.getK()) {
                back = JsonBack.success(isDelete.getK());
            } else {
                //司机删除失败的时候，需要处理后端处理的业务信息
                CodeStatus codeStatus = DRIVER_DELETE_ERROR.getCodeStatus();
                back = JsonBack.instance(codeStatus.getCode(), codeStatus.getMsg() + isDelete.getV(), false);
            }

        } catch (BusinessException e) {
            back = JsonBack.error(e);
            LOGGER.error("删除参数", e);
        } catch (Exception e) {
            back = JsonBack.error(SYSTEM_CODE_ERROR);
            LOGGER.error("删除参数", e);
        }
        return back;
    }

    /**
     * 查询司机状态
     *
     * @author Anson
     * @date 17-8-23
     * @since 1.0.6
     */
    @RequestMapping("/getStatus")
    public JsonBack<List<Map<String, Object>>> getStatus() {
        try {
            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
            for (DriverRegisterBusRelative.RelativeStatus c : DriverRegisterBusRelative.RelativeStatus.values()) {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("key", c.getCode());
                map.put("msg", c.getMsg());
                list.add(map);
            }
            return JsonBack.success(list);
        } catch (Exception e) {
            LOGGER.error("获取司机状态异常", e);
            return JsonBack.error(SYSTEM_CODE_ERROR);
        }
    }
}
